<?php
require('config.php');

        $user_id=$_REQUEST['user_id'];
        $json=$_REQUEST['json'];
        $pay_way=$_REQUEST['pay_way'];

        // $user_id=54;
        // $json='[{orderId:107}]';
        // $pay_way='1';

        $json=json_decode($json,true);
		$sql="select * from `".$oto."_users` where `userId`='".$user_id."' LIMIT 1";
		$result=$db->query($sql);
		while($row=$result->fetch_assoc()){
			$user_info[]=$row;//将取得的所有数据赋值给person_info数组
		}
		$pay_money=0;
		$yhq_pan_id=1;
		for($i=0;$i<count($json);$i++)
		{
			$order_id=$json[$i]['orderId'];
			$sql="select * from `".$oto."_orders` where `orderId`='".$order_id."' LIMIT 1";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$order[$i]=$row;//将取得的所有数据赋值给person_info数组
			}
			//$pay_money+=$order[$i]['needPay']+$order[$i]['deliverMoney'];
			$pay_money+=$order[$i]['needPay'];
			if($order[$i]['isPay']==1 || $order[$i]['isPay']=='1')
			{
				$data[0]['pan']=-3;
				$data[0]['msg']=$order[$i]['orderNo']."已付过款";
				echo json_encode($data);
				exit();
			}
			if($order[$i]['couponId']==0 || $order[$i]['couponId']==null);
			else $yhq_pan_id=0;
		}
		if($user_info[0]['userMoney']>=$pay_money)
		{
			$data[0]['msg']='';
			$lin_max_pan=0;
			for($i=0;$i<count($json);$i++)//判断库存等操作
			{
				$order_id=$json[$i]['orderId'];
				$sql="select * from `".$oto."_order_goods` where `orderId`='".$order_id."'";
				$result=$db->query($sql);
				while($row=$result->fetch_assoc()){
					$lin_goods[$i][]=$row;//将取得的所有数据赋值给person_info数组
				}
				for($j=0;$j<count($lin_goods);$j++)
				{
					$goods_id=$lin_goods[$i][$j]['goodsId'];
					$goods_attr_id=$lin_goods[$i][$j]['goodsAttrId'];
					$goods_num=$lin_goods[$i][$j]['goodsNums'];
					$lin_pan=0;
					$sql="select * from `".$oto."_goods` where `goodsId`='".$goods_id."' LIMIT 1";
					$result=$db->query($sql);
					while($row=$result->fetch_assoc()){
						$lin_goods_info[$j]=$row;//将取得的所有数据赋值给person_info数组
					}
					if($lin_goods_info[$j]['goodsStock']<$goods_num)
					{
						$lin_pan=1;
						$lin_max_pan=1;
					}
					else
					{
						if($goods_attr_id==null || $goods_attr_id=="")
						{

						}
						else
						{
							$goods_attr_id=explode(',',$goods_attr_id);
							for($k=0;$k<count($goods_attr_id);$k++)
							{
								$attr_id=$goods_attr_id[$k];
								$sql="select * from `".$oto."_goods_attributes` where `id`='".$attr_id."' LIMIT 1";
								$result=$db->query($sql);
								while($row=$result->fetch_assoc()){
									$attr_info[$k]=$row;//将取得的所有数据赋值给person_info数组
								}
								if($attr_info[$k]['attrStock']<$goods_num)
								{
									$lin_pan=1;
									$lin_max_pan=1;
								}
							}
						}
					}
					if($lin_pan==1)
					{
						$data[0]['pan']=-3;
						$data[0]['msg'].=$lin_goods_info[$j]['goodsName'].'库存不足！ ';
						echo json_encode($data);
						exit();
					}
				}
			}
			$time=time();
			/*优惠券验证是否过期*/
			$sql="select * from `".$oto."_youhui_user_link`,`".$oto."_youhui` where ".$oto."_youhui_user_link.user_id='{$user_id}' and u_is_effect='1' and ".$oto."_youhui_user_link.youhui_id=".$oto."_youhui.id";
			$result=$db->query($sql);
			while($row=$result->fetch_assoc()){
				$yhq_info[]=$row;//将取得的所有数据赋值给person_info数组
			}
			if(!isset($yhq_info))
			{
				if($yhq_pan_id==0)
				{
					$data[0]['pan']=-2;
					$data[0]['msg']='优惠券已过期或不存在';
					echo json_encode($data);
					exit();
				}
			}
			if(isset($yhq_info))
			{
				for($i=0;$i<count($yhq_info);$i++)
				{
					if($yhq_info[$i]['end_time']<$time)
					{
						$youhui_id=$yhq_info[$i]['youhui_id'];
						$sql="update ".$oto."_youhui_user_link set u_is_effect='0' where user_id='{$user_id}' and youhui_id='{$youhui_id}'";
						$result=$db->query($sql);
					}
				}
			}
			
			for($i=0;$i<count($json);$i++)
			{
				$order_id=$json[$i]['orderId'];
				$sql="select * from `".$oto."_orders` where `orderId`='".$order_id."'";
				$result=$db->query($sql);
				while($row=$result->fetch_assoc()){
					$order_youhui_info[$i]=$row;//将取得的所有数据赋值给person_info数组
				}
				$order_youhui_id=$order_youhui_info[$i]['couponId'];
				$sql="select * from `".$oto."_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
				$result=$db->query($sql);
				while($row=$result->fetch_assoc()){
					$yhq_yz[]=$row;//将取得的所有数据赋值给person_info数组
				}
				if(!isset($yhq_yz) && $order_youhui_id!=0 && $order_youhui_id!='0')
				{
					if($yhq_pan_id==0)
					{
						$data[0]['pan']=-2;
						$data[0]['msg']='优惠券已过期或不存在';
						echo json_encode($data);
						exit();
					}
				}
				else
				{
					if($order_youhui_id==0 || $order_youhui_id=='0');
					else if($yhq_yz[0]['surplus']<1)
					{
						if($yhq_pan_id==0)
						{
							$data[0]['pan']=-2;
							$data[0]['msg']='优惠券已过期或不存在';
							echo json_encode($data);
							exit();
						}
					}
				}
			}
			/*优惠券验证end*/
			if($lin_max_pan==0)//通过验证了
			{
				//减少商品库存
				for($i=0;$i<count($json);$i++)
				{
					$order_id=$json[$i]['orderId'];
					$sql="select * from `".$oto."_order_goods` where `orderId`='".$order_id."'";
					$result=$db->query($sql);
					while($row=$result->fetch_assoc()){
						$lin_goods[$i][]=$row;//将取得的所有数据赋值给person_info数组
					}
					for($j=0;$j<count($lin_goods);$j++)
					{
						$goods_id=$lin_goods[$i][$j]['goodsId'];
						$goods_attr_id=$lin_goods[$i][$j]['goodsAttrId'];
						$goods_num=$lin_goods[$i][$j]['goodsNums'];
						$lin_pan=0;
						$sql="select * from `".$oto."_goods` where `goodsId`='".$goods_id."' LIMIT 1";
						$result=$db->query($sql);
						while($row=$result->fetch_assoc()){
							$lin_goods_info[$j]=$row;//将取得的所有数据赋值给person_info数组
						}
						$goodsStock=$lin_goods_info[$j]['goodsStock'];
						$hgoodsStock=$goodsStock-$goods_num;
						$hsaleCount=$lin_goods_info[$j]['saleCount']+$goods_num;
						$sql="update ".$oto."_goods set goodsStock='{$hgoodsStock}' where goodsId='{$goods_id}'";
						$result=$db->query($sql);
						if($goodsStock<$goods_num)
						{
							// $lin_pan=1;
							// $lin_max_pan=1;
						}
						else
						{
							if($goods_attr_id==null || $goods_attr_id=="")
							{

							}
							else
							{
								$goods_attr_id=explode(',',$goods_attr_id);
								for($k=0;$k<count($goods_attr_id);$k++)//减少属性库存
								{
									$attr_id=$goods_attr_id[$k];
									$sql="select * from `".$oto."_goods_attributes` where `id`='".$attr_id."' LIMIT 1";
									$result=$db->query($sql);
									while($row=$result->fetch_assoc()){
										$attr_info[$k]=$row;//将取得的所有数据赋值给person_info数组
									}
									$attrStock=$attr_info[$k]['attrStock'];
									$hattrStock=$attrStock-$goods_num;
									$sql="update ".$oto."_goods_attributes set attrStock='{$hattrStock}' where id='{$attr_id}'";
									$result=$db->query($sql);
									// if($attr_info[$k]['attrStock']<$goods_num)
									// {
									// 	$lin_pan=1;
									// 	$lin_max_pan=1;
									// }
								}
							}
						}
						// if($lin_pan==1)
						// {
						// 	$data[0]['pan']=-3;
						// 	$data[0]['msg'].=$lin_goods_info[$j]['goodsName'].'库存不足！\n\r';
						// }
					}
				}
				/****************判断库存等验证通过时修改订单状态以及减少用户余额****************/
				for($i=0;$i<count($json);$i++)
				{
					$order_id=$json[$i]['orderId'];
					$sql="update ".$oto."_orders set orderStatus='0',payType='{$pay_way}',paytime='{$time}',isPay='1' where orderId='{$order_id}'";
					$result=$db->query($sql);
					$createTime=date('Y-m-d H:i:s');
					$sql="INSERT INTO ".$oto."_log_orders (`orderId`,`logContent`,`logUserId`,`logType`,`logTime`) VALUES ('$order_id','下单成功','$user_id','0','$createTime')";
            		$result=$db->query($sql);
					$sql="select * FROM ".$oto."_orders where orderId='{$order_id}'";
					$result=$db->query($sql);
					while($row=$result->fetch_assoc()){
						$score_order_lin[$i]=$row;//将取得的所有数据赋值给person_info数组
					}
					$order_no=$score_order_lin[$i]['orderNo'];
					$needPay_lin=$score_order_lin[$i]['needPay'];
					$user_score_lin=$user_info[0]['userScore']+$needPay_lin;
					$user_money_lin=$user_info[0]['userMoney']-$needPay_lin;
					// $sql="INSERT INTO ".$oto."_score_record (`userid`,`orderNo`,`score`,`totalscore`,`time`,`IncDec`,`type`) VALUES ('$user_id','$order_no','$needPay_lin','$user_score_lin','$time','1','1')";
     //        		$result=$db->query($sql);
            		if($pay_way==3) $pay_way_lin=0;
            		if($pay_way==1) $pay_way_lin=1;
            		if($pay_way==2) $pay_way_lin=2;
            		$sql="INSERT INTO ".$oto."_money_record (`userid`,`orderNo`,`money`,`balance`,`time`,`IncDec`,`type`,`remark`,`payWay`) VALUES ('$user_id','$order_no','$needPay_lin','$user_money_lin','$time','0','1','购买商品','$pay_way_lin')";
            		//file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
            		$result=$db->query($sql);
				}
				$user_money=$user_info[0]['userMoney']-$pay_money;
				$user_score=$user_info[0]['userScore']+$pay_money;
				// $sql="update ".$oto."_users set userMoney='{$user_money}',userScore='{$user_score}' where userId='{$user_id}'";
				// $result=$db->query($sql);
				$sql="update ".$oto."_users set userMoney='{$user_money}' where userId='{$user_id}'";
				$result=$db->query($sql);
				if($result)
				{
					$data[0]['pan']=1;
				}
				else
				{
					for($i=0;$i<count($json);$i++)
					{
						$order_id=$json[$i]['orderId'];
						$sql="update ".$oto."_orders set orderStatus='-2' where orderId='{$order_id}'";
						$result=$db->query($sql);
					}
					$data[0]['pan']=-2;
					$data[0]['msg']='支付异常';
				}
				/********************************/

				/************增加优惠券使用记录并减少未使用优惠券**************/
				for($i=0;$i<count($json);$i++)
				{
					$order_id=$json[$i]['orderId'];
					$sql="select * from `".$oto."_orders` where `orderId`='".$order_id."'";
					$result=$db->query($sql);
					while($row=$result->fetch_assoc()){
						$order_youhui_info[$i]=$row;//将取得的所有数据赋值给person_info数组
					}
					$order_youhui_id=$order_youhui_info[$i]['couponId'];
					if($order_youhui_id!=0 && $order_youhui_id!='0')
					{
						$order_youhui_id=$order_youhui_info[0]['couponId'];
						$order_youhui_money=$order_youhui_info[0]['couponMoney'];
						$sql="select * from `".$oto."_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
						$result=$db->query($sql);
						while($row=$result->fetch_assoc()){
							$yhq_yz[]=$row;//将取得的所有数据赋值给person_info数组
						}
						if(isset($yhq_yz))
						{
							if($yhq_yz[0]['surplus']>1)
							{
								$surplus=$yhq_yz[0]['surplus']-1;
								$l_shopId=$yhq_yz[0]['shop_id'];
								$sql="update ".$oto."_youhui_user_link set surplus='{$surplus}' where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
								$result=$db->query($sql);
								$sql="INSERT INTO ".$oto."_youhui_use_record (`youhui_id`,`userId`,`shopId`,`useTime`,`orderId`,`money`) VALUES ('$order_youhui_id','$user_id','$l_shopId','$time','$order_id','$order_youhui_money')";
            					$result=$db->query($sql);
							}
							else
							{
								$sql="DELETE FROM `".$oto."_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
								$result=$db->query($sql);
								$l_shopId=$yhq_yz[0]['shop_id'];
								$sql="INSERT INTO ".$oto."_youhui_use_record (`youhui_id`,`userId`,`shopId`,`useTime`,`orderId`,`money`) VALUES ('$order_youhui_id','$user_id','$l_shopId','$time','$order_id','$order_youhui_money')";
            					$result=$db->query($sql);
							}
						}
					}
					
				}
				/**************************/
			}
		}
		else
		{
			$data[0]['pan']=-1;
		}
		//file_put_contents("tsxx.txt", "\r\n".111."\r\n", FILE_APPEND);
		echo json_encode($data);
?>